package com.jnu.ilearn;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.jnu.ilearn.bean.DataBank;
import com.jnu.ilearn.bean.PointRecord;
import com.jnu.ilearn.bean.SeatItem;
import com.jnu.ilearn.bean.User;
import com.jnu.ilearn.utils.DataLoader;
import com.jnu.ilearn.utils.SeatUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SecondFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SecondFragment extends Fragment {

    private List<SeatItem> seatItems =new ArrayList<>();    //视图下的座位信息
    private List<SeatItem> seatItemList=new ArrayList<>();      //数据库传回的座位信息
    private GridView seatGridview;
    private TextView restSeatView;
    private SecondFragment.SeatItemAdapter seatItemAdapter;
    private DataLoader dataLoader;
    private TextView quitSeat;
    private View rootView;
    private User user;
    private int restSeat;   //剩余空位数
    private int coin_sum;   //拥有金币总数
    private DataBank dataBank;
    private List<PointRecord> pointRecordList;
    boolean isOnStart=false;

    public SecondFragment() {
        // Required empty public constructor
    }

    @Override
    public void onStart() {
        if(isOnStart==true){
            super.onStart();
        }
        else {
            dataLoader=new DataLoader();
            Handler handler=new Handler(Looper.getMainLooper()){
                @Override
                public void handleMessage(@NonNull Message msg) {
                    super.handleMessage(msg);
                    seatItemList=dataLoader.GetSeat();
                    UpdateSeatItems();
                    InitItems();
                }
            };
            dataLoader.LoadSeat(handler);
            super.onStart();
        }
    }

    public static SecondFragment newInstance() {
        SecondFragment fragment = new SecondFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView=inflater.inflate(R.layout.fragment_second,container,false);
        quitSeat=rootView.findViewById(R.id.quit_seat);
        isOnStart=true;
        dataLoader=new DataLoader();
        Handler handler=new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                seatItemList=dataLoader.GetSeat();
                InitSeatItems();
                InitItems();        //初始化costItemList的数据
            }
        };
        dataLoader.LoadSeat(handler);
        return rootView;
    }

    //接收更改的座位信息
    ActivityResultLauncher<Intent> launcherRegister = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>(){
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data=result.getData();
            int resultCode = result.getResultCode();
            //确认占座后
            if(resultCode==1)
            {
                int position=data.getIntExtra("position",0);
                String studyContent=data.getStringExtra("studyContent");
                seatItems.get(position).setUser(user.getAccount());
                seatItems.get(position).setState(true);
                seatItems.get(position).setContent(studyContent);
                seatItemAdapter.notifyDataSetChanged();
                restSeat--;
                restSeatView.setText("剩余空座"+restSeat);
                Toast.makeText(SecondFragment.this.getContext(),"占座成功",Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(SecondFragment.this.getContext(),"已取消",Toast.LENGTH_LONG).show();
            }
        }
    });

    private void tipDialog(int position) {
        Intent intent=new Intent(SecondFragment.this.getContext(),SitDownActivity.class);
        intent.putExtra("seatId",seatItems.get(position).getSeatID());
        intent.putExtra("user",user.getAccount());
        intent.putExtra("position",position);
        launcherRegister.launch(intent);
    }

    private void UpdateSeatItems(){
        int i=24;
        seatItems.clear();
        for(int j=0;j<6;j++){
            seatItems.add(seatItemList.get(i));
            i++;
            seatItems.add(new SeatItem(false,"null",null,"null",0));
            seatItems.add(seatItemList.get(i));
            i++;
            seatItems.add(seatItemList.get(i));
            i++;
            seatItems.add(new SeatItem(false,"null",null,"null",0));
            seatItems.add(seatItemList.get(i));
            i++;
        }
    }

    private void InitSeatItems(){
        int i=24;
        seatItems.add(new SeatItem(false,"null",null,"null",0));
        seatItems.clear();
        for(int j=0;j<6;j++){
            seatItems.add(seatItemList.get(i));
            i++;
            seatItems.add(new SeatItem(false,"null",null,"null",0));
            seatItems.add(seatItemList.get(i));
            i++;
            seatItems.add(seatItemList.get(i));
            i++;
            seatItems.add(new SeatItem(false,"null",null,"null",0));
            seatItems.add(seatItemList.get(i));
            i++;
        }
    }

    private void InitItems(){
        dataBank=new DataBank(SecondFragment.this.getContext());
        dataBank.loadData();
        pointRecordList=dataBank.getPointRecordList();
        user=dataBank.getUser();
        if(user.getIdentity().equals("student")){
            coin_sum=user.getPoint();
        }
        restSeat=0;
        //将适配器上的数据传给costItemList
        seatGridview =(GridView) rootView.findViewById(R.id.my_grid_view);
        seatItemAdapter=new SeatItemAdapter(SecondFragment.this.getContext(),R.layout.itemlayout_2,seatItems);
        seatGridview.setAdapter(seatItemAdapter);

        if(user.getIdentity().equals("student")){
            quitSeat.setOnClickListener(new StudentListener());
            seatGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if(seatItems.get(position).isState()==true){
                        if(seatItems.get(position).getUser().equals(user.getAccount())){
                            AlertDialog.Builder ab=new AlertDialog.Builder(SecondFragment.this.getContext());  //普通消息框
                            ab.setTitle("提示");  //设置标题
                            ab.setMessage("您好，是否退座？");//设置消息内容
                            ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    SeatUtils seatUtils=new SeatUtils();
                                    Handler handler=new Handler(Looper.getMainLooper()){
                                        @Override
                                        public void handleMessage(@NonNull Message msg) {
                                            super.handleMessage(msg);
                                            if(seatUtils.isDepart()){
                                                int coin=CoinSum(seatItems.get(position).getBeginTime());
                                                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                                String dateText=dateFormat.format(seatItems.get(position).getBeginTime().getTime());
                                                String string=dateText+" "+seatItems.get(position).getContent();
                                                pointRecordList.add(new PointRecord(string,coin));
                                                user.setPoint(coin);
                                                dataBank.saveData();
                                                restSeat++;
                                                restSeatView.setText("剩余空座"+restSeat);
                                                seatItems.get(position).setState(false);
                                                seatItems.get(position).setContent(null);
                                                seatItems.get(position).setUser(null);
                                                seatItems.get(position).setBeginTime(null);
                                                seatItemAdapter.notifyDataSetChanged();
                                                new AlertDialog.Builder(SecondFragment.this.getContext()).setTitle("提示").setMessage("退座成功！").show();
                                            }
                                            else {
                                                new AlertDialog.Builder(SecondFragment.this.getContext()).setTitle("提示").setMessage("退座失败！").show();
                                            }
                                        }
                                    };
                                    ArrayList<Integer> seatId=new ArrayList<>();
                                    seatId.add(seatItems.get(position).getSeatID());
                                    seatUtils.DepartSeat(handler,seatId);
                                }
                            });//设置确定按钮
                            ab.setNegativeButton("取消",null);
                            ab.show();//显示弹出框
                        }
                        else {
                            AlertDialog.Builder ab=new AlertDialog.Builder(SecondFragment.this.getContext());  //普通消息框
                            ab.setTitle("提示");  //设置标题
                            ab.setMessage("您好，此座位也被人占用。");//设置消息内容
                            ab.setPositiveButton("确定",null);//设置确定按钮
                            ab.show();//显示弹出框
                        }
                    }
                    if(seatItems.get(position).isState()==false){
                        if(IsOverLoad()){
                            AlertDialog.Builder ab=new AlertDialog.Builder(SecondFragment.this.getContext());  //普通消息框
                            ab.setTitle("提示");  //设置标题
                            ab.setMessage("您已占了四个座位，请勿多占，谢谢配合。");//设置消息内容
                            ab.setPositiveButton("确定",null);
                            ab.show();//显示弹出框
                        }
                        else {
                            AlertDialog.Builder ab=new AlertDialog.Builder(SecondFragment.this.getContext());  //普通消息框
                            ab.setTitle("提示");  //设置标题
                            ab.setMessage("是否占座");//设置消息内容
                            ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dataLoader=new DataLoader();
                                    Handler handler=new Handler(Looper.getMainLooper()){
                                        @Override
                                        public void handleMessage(@NonNull Message msg) {
                                            super.handleMessage(msg);
                                            seatItemList=dataLoader.GetSeat();
                                            UpdateSeatItems();
                                            if(seatItems.get(position).isState()==true){
                                                AlertDialog.Builder alBer=new AlertDialog.Builder(SecondFragment.this.getContext());  //普通消息框
                                                alBer.setTitle("提示");  //设置标题
                                                alBer.setMessage("对不起，您慢了一步，此座位刚被别人占了，抱歉。");//设置消息内容
                                                alBer.setPositiveButton("确定",null);
                                                InitItems();
                                                alBer.show();
                                            }
                                            else {
                                                tipDialog(position);
                                            }

                                        }
                                    };
                                    dataLoader.LoadSeat(handler);
                                }
                            });//设置确定按钮
                            ab.setNegativeButton("取消",null);
                            ab.show();//显示弹出框
                        }
                    }
                }
            });
        }
        else if(user.getIdentity().equals("manager")){
            quitSeat.setVisibility(View.GONE);
            seatGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if(seatItems.get(position).isState()==false){
                        //无人时的操作
                        new AlertDialog.Builder(SecondFragment.this.getContext()).setTitle("提示").setMessage("无人！").show();
                    }
                    else {
                        //有人时显示信息
                        String userString="占座者："+seatItems.get(position).getUser();
                        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String beginTime="开始时间："+simpleDateFormat.format(seatItems.get(position).getBeginTime().getTime());
                        AlertDialog.Builder a=new AlertDialog.Builder(SecondFragment.this.getContext());
                        a.setTitle("您好");
                        a.setMessage(userString+"\n"+beginTime);
                        a.setPositiveButton("强制退座", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                SeatUtils seatUtils=new SeatUtils();
                                Handler handler=new Handler(Looper.getMainLooper()){
                                    @Override
                                    public void handleMessage(@NonNull Message msg) {
                                        super.handleMessage(msg);
                                        if(seatUtils.isDepart()){
                                            restSeat++;
                                            restSeatView.setText("剩余空座"+restSeat);
                                            seatItems.get(position).setState(false);
                                            seatItems.get(position).setContent(null);
                                            seatItems.get(position).setUser(null);
                                            seatItems.get(position).setBeginTime(null);
                                            seatItemAdapter.notifyDataSetChanged();
                                            new AlertDialog.Builder(SecondFragment.this.getContext()).setTitle("提示").setMessage("退座成功！").show();
                                        }
                                        else {
                                            new AlertDialog.Builder(SecondFragment.this.getContext()).setTitle("提示").setMessage("退座失败！").show();
                                        }
                                    }
                                };
                                ArrayList<Integer> seatId=new ArrayList<>();
                                seatId.add(seatItems.get(position).getSeatID());
                                seatUtils.DepartSeat(handler,seatId);
                            }
                        });
                        a.setNegativeButton("取消",null);
                        a.show();
                    }
                }
            });
        }

        for(int k=24;k<48;k++){
            if(seatItemList.get(k).isState()==false){
                restSeat++;
            }
        }
        restSeatView=rootView.findViewById(R.id.rest_seat);
        restSeatView.setText("剩余空座"+restSeat);
    }

    private class SeatItemAdapter extends ArrayAdapter<SeatItem> {
        private int resourceId;

        //适配器的构造函数，把要适配的数据传入这里
        public SeatItemAdapter(@NonNull Context context, int resource, @NonNull List<SeatItem> objects) {
            super(context, resource, objects);
            resourceId=resource;
        }

        //设置显示的图片
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            SeatItem seatItem=(SeatItem) getItem(position);
            View view;
            SeatItemAdapter.ViewHolder viewHolder;
            if(convertView==null){
                view= LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
                viewHolder=new SeatItemAdapter.ViewHolder();
                viewHolder.imageButton=(ImageButton) view.findViewById(R.id.imageButton);
                view.setTag(viewHolder);    // 将ViewHolder存储在View中
            }else{
                view=convertView;
                viewHolder = (SeatItemAdapter.ViewHolder) view.getTag(); // 重新获取ViewHolder
            }
            if(seatItem.getSeatID()==0){
                seatItem.setSeatImageId(R.drawable.no_seat);
            }
            else {
                if(seatItem.isState()==true){
                    if(seatItem.getUser().equals(user.getAccount())){
                        seatItem.setSeatImageId(R.drawable.my_seat);
                    }
                    else {
                        seatItem.setSeatImageId(R.drawable.seat_1);
                    }
                }
                else {
                    seatItem.setSeatImageId(R.drawable.seat_2);
                }
            }
            viewHolder.imageButton.setImageDrawable(getResources().getDrawable(seatItem.getSeatImageId()));

            return view;
        }

        class ViewHolder{
            ImageButton imageButton;
        }
    }

    class StudentListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.quit_seat:
                    //一键退座点击事件
                    AlertDialog.Builder ab=new AlertDialog.Builder(SecondFragment.this.getContext());  //普通消息框
                    ab.setTitle("提示");  //设置标题
                    ab.setMessage("是否全部退座？");//设置消息内容
                    ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ArrayList<Integer> seatIds=new ArrayList<>();
                            ArrayList<Integer> positions=new ArrayList<>();
                            for(int i=0;i<36;i++){
                                if(seatItems.get(i).getUser()!=null){
                                    if(seatItems.get(i).getUser().equals(user.getAccount())){
                                        seatIds.add(seatItems.get(i).getSeatID());
                                        positions.add(i);
                                    }
                                }
                            }
                            SeatUtils seatUtils=new SeatUtils();
                            Handler handler=new Handler(Looper.getMainLooper()){
                                @Override
                                public void handleMessage(@NonNull Message msg) {
                                    super.handleMessage(msg);
                                    if(seatUtils.isDepart()){
                                        for(int i=0;i<positions.size();i++){
                                            int coin=CoinSum(seatItems.get(positions.get(i)).getBeginTime());
                                            coin_sum+=coin;
                                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                            String dateText=dateFormat.format(seatItems.get(positions.get(i)).getBeginTime().getTime());
                                            String message=dateText+" "+seatItems.get(positions.get(i)).getContent();
                                            pointRecordList.add(new PointRecord(message,coin));
                                            restSeat++;
                                            seatItems.get(positions.get(i)).setState(false);
                                            seatItems.get(positions.get(i)).setContent(null);
                                            seatItems.get(positions.get(i)).setUser(null);
                                            seatItems.get(positions.get(i)).setBeginTime(null);
                                        }
                                        user.setPoint(coin_sum);
                                        dataBank.saveData();
                                        restSeatView.setText("剩余空座"+restSeat);
                                        seatItemAdapter.notifyDataSetChanged();
                                        new AlertDialog.Builder(SecondFragment.this.getContext()).setTitle("提示").setMessage("退座成功！").show();
                                    }
                                    else {
                                        new AlertDialog.Builder(SecondFragment.this.getContext()).setTitle("提示").setMessage("退座失败！").show();
                                    }
                                }
                            };
                            seatUtils.DepartSeat(handler,seatIds);
                        }
                    });//设置确定按钮
                    ab.setNegativeButton("取消",null);
                    ab.show();//显示弹出框
            }
        }
    }

    private int CoinSum(Calendar beginTime){
        int coins=0;
        Calendar now=Calendar.getInstance();
        int days=now.get(Calendar.DAY_OF_MONTH)-beginTime.get(Calendar.DAY_OF_MONTH);
        int hours=now.get(Calendar.HOUR_OF_DAY)-beginTime.get(Calendar.HOUR_OF_DAY);
        int minutes=now.get(Calendar.MINUTE)-beginTime.get(Calendar.MINUTE);
        coins=(int)(days*144+hours*6+minutes*0.1);
        return coins;
    }

    private boolean IsOverLoad(){
        boolean overload=false;
        int sum=0;
        for(int i=0;i<36;i++){
            if(user.getAccount().equals(seatItems.get(i).getUser())){
                sum++;
            }
        }
        if(sum>=4){
            overload=true;
        }
        return overload;
    }
}